import { createMqttClient, mcbTopicPrefix } from "@/utils/mqttClient"
export default {
  data() {
    return {
      client: null,
      isConnect: false
    }
  },
  beforeDestroy() {
    clearInterval(this.syncTimer)
    this.notifyer && this.notifyer.close()
    this.client && this.client.end()
    clearInterval(this.fortime)
  },
  methods: {
    initMqtt(fn1, fn2, fn3) {
      this.client = new createMqttClient(this, onMessageArrived(fn1), onConnect(this, fn2), onError(fn3))
    },
    subscribe(info, productkey = "") {
      const keys = ["MCB", "ACB-A", "ACB-H", "PD", "CDGA-4G", "CDGA-E"]
      if (!productkey) {
        keys.forEach((item) => {
          if (info.productType.indexOf(item) > -1) {
            productkey = item
          }
        })
      }

      const topic = `${mcbTopicPrefix}gateway/${productkey}/${info.gatewayCode}/up`
      console.log(topic)
      this.client.subscribe(topic)
    },
    pursubscribe(key, code = "") {
      const topic = `${mcbTopicPrefix}gateway/${key}/${code}/up`
      console.log(topic)
      this.client.subscribe(topic)
    }
  }
}
function onMessageArrived(callback) {
  return function (topic, message) {
    // console.log(message);
    let payload
    try {
      payload = JSON.parse(message.toString())
    } catch (err) {
      payload = {}
    }
    callback(payload)
  }
}
function onConnect(self, callback) {
  return function () {
    self.isConnect = true
    callback && callback()
  }
}
function onError(error) {
  return function () {
    console.log("连接失败了", error)
  }
}
